package org.jeecg.modules.business.takestockplan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.service.IBasicMaterialService;
import org.jeecg.modules.basic.materialtype.service.IBasicMaterialTypeService;
import org.jeecg.modules.basic.print.entity.PrintConfig;
import org.jeecg.modules.basic.print.entity.WmsDocumentTypeStatus;
import org.jeecg.modules.basic.print.service.IPrintConfigService;
import org.jeecg.modules.basic.print.service.IWmsDocumentTypeStatusService;
import org.jeecg.modules.basic.unit.entity.BasicUnit;
import org.jeecg.modules.basic.unit.service.IBasicUnitService;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouse;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseArea;
import org.jeecg.modules.basic.warehouse.entity.WmsBasicWarehouseAreaLocation;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseAreaLocationMapper;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseAreaMapper;
import org.jeecg.modules.basic.warehouse.mapper.WmsBasicWarehouseMapper;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaLocationService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseAreaService;
import org.jeecg.modules.basic.warehouse.service.IWmsBasicWarehouseService;
import org.jeecg.modules.basic.warehouseGroup.service.IWmsBasicWarehouseGroupService;
import org.jeecg.modules.business.repertory.entity.WmsRepertory;
import org.jeecg.modules.business.repertory.mapper.WmsRepertoryMapper;
import org.jeecg.modules.business.repertory.service.IWmsRepertoryService;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlan;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanDifferenceMaterial;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanExecute;
import org.jeecg.modules.business.takestockplan.entity.TakeStockPlanExecuteMaterial;
import org.jeecg.modules.business.takestockplan.entity.VO.TakeStockPlanExecuteAddVO;
import org.jeecg.modules.business.takestockplan.entity.VO.TakeStockPlanExecuteMaterialVO;
import org.jeecg.modules.business.takestockplan.entity.VO.TakeStockPlanExecuteVO;
import org.jeecg.modules.business.takestockplan.entity.constant.TakeStockPlanStatusConstant;
import org.jeecg.modules.business.takestockplan.mapper.TakeStockPlanExecuteMapper;
import org.jeecg.modules.business.takestockplan.mapper.TakeStockPlanExecuteMaterialMapper;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanDifferenceMaterialService;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanExecuteMaterialService;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanExecuteService;
import org.jeecg.modules.business.takestockplan.service.ITakeStockPlanService;
import org.jeecg.modules.basic.warehouseGroup.entity.WmsBasicWarehouseGroup;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 盘点执行
 * @Author: jeecg-boot
 * @Date: 2023-08-04
 * @Version: V1.0
 */
@Service
public class TakeStockPlanExecuteServiceImpl extends ServiceImpl<TakeStockPlanExecuteMapper, TakeStockPlanExecute> implements ITakeStockPlanExecuteService {

    @Autowired
    private TakeStockPlanExecuteMapper takeStockPlanExecuteMapper;
    @Autowired
    private TakeStockPlanExecuteMaterialMapper takeStockPlanExecuteMaterialMapper;

    @Autowired
    private ITakeStockPlanService takeStockPlanService;

    @Autowired
    private IBasicMaterialTypeService basicMaterialTypeService;

    @Autowired
    private IBasicMaterialService basicMaterialService;

    @Autowired
    private IWmsRepertoryService wmsRepertoryService;

    @Autowired
    private ITakeStockPlanExecuteMaterialService takeStockPlanExecuteMaterialService;

    @Autowired
    private WmsRepertoryMapper repertoryMapper;

    @Autowired
    private IWmsBasicWarehouseGroupService warehouseGroupService;

    @Autowired
    private WorkFlowService workFlowService;

    @Autowired
    private IPrintConfigService printConfigService;

    @Autowired
    private IWmsDocumentTypeStatusService documentTypeStatusService;

    @Autowired
    private IWmsBasicWarehouseService warehouseService;

    @Autowired
    private IWmsBasicWarehouseAreaService warehouseAreaService;

    @Autowired
    private IWmsBasicWarehouseAreaLocationService warehouseAreaLocationService;

    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    @Autowired
    private IBasicUnitService unitService;

    @Autowired
    private WmsBasicWarehouseMapper warehouseMapper;
    @Autowired
    private WmsBasicWarehouseAreaMapper warehouseAreaMapper;
    @Autowired
    private WmsBasicWarehouseAreaLocationMapper warehouseAreaLocationMapper;
    @Autowired
    private ITakeStockPlanDifferenceMaterialService takeStockPlanDifferenceMaterialService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        TakeStockPlanExecute byId = this.getById(id);
        if (TakeStockPlanStatusConstant.SUBMITTED.equals(byId.getDocumentStatus())) {
            throw new JeecgBootException("单据状态为已提交，不能删除");
        }
        // 盘点计划改为未执行,状态变为待执行
        if ("1".equals(byId.getCode().split("-")[1])) {
            TakeStockPlan plan = takeStockPlanService.getById(byId.getWmsTakeStockPlanId());
            plan.setExecuteFlag("0");
            plan.setDocumentStatus("2");
            takeStockPlanService.updateById(plan);
        }

        takeStockPlanExecuteMaterialMapper.deleteByMainId(id);
        takeStockPlanExecuteMapper.deleteById(id);
    }

    /**
     * 分页
     *
     * @param page
     * @param takeStockPlanExecute
     * @return
     */
    @Override
    public Page<TakeStockPlanExecuteVO> listByPage(Page<TakeStockPlanExecuteVO> page, TakeStockPlanExecuteVO takeStockPlanExecute) {
        List<TakeStockPlanExecuteVO> list = takeStockPlanExecuteMapper.listByPage(page, takeStockPlanExecute);
        List<String> codes = takeStockPlanExecuteMapper.maxCode();
        for (TakeStockPlanExecuteVO vo : list) {
            if (codes.contains(vo.getCode())) {
                vo.setIsNew("1");
            }
        }
        return page.setRecords(list);
    }

    /**
     * 获取新增时详情
     *
     * @param wmsTakeStockPlanId
     * @return
     */
    @Override
    public TakeStockPlanExecuteMaterialVO getAddDetail(String wmsTakeStockPlanId) {
        TakeStockPlan plan = takeStockPlanService.getById(wmsTakeStockPlanId);
        TakeStockPlanExecuteMaterialVO vo = BeanUtil.toBean(plan, TakeStockPlanExecuteMaterialVO.class);
        vo.setWmsTakeStockPlanId(wmsTakeStockPlanId);
        vo.setTakeStockPlanCode(plan.getCode());
        vo.setWmsTakeStockPlanName(plan.getName());
        // 根据仓库，库区，物料分类，物料编码 查询即时库存
        QueryWrapper<WmsRepertory> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(plan.getMaterialTypeId())) {
            List<String> typeIds = basicMaterialTypeService.listIdsByPid(plan.getMaterialTypeId());
            List<BasicMaterial> list = basicMaterialService.list(new LambdaQueryWrapper<BasicMaterial>()
                    .in(BasicMaterial::getMaterialTypeId, typeIds));
            if (CollectionUtils.isNotEmpty(list)) {
                List<String> materialIds = list.stream().map(BasicMaterial::getId).collect(Collectors.toList());
                wrapper.in("material_id", materialIds);
            }
        }
        if (StringUtils.isNotBlank(plan.getMaterialId())) {
            wrapper.in("material_id", Arrays.asList(plan.getMaterialId().split(",")));
        }
        wrapper.eq(StringUtils.isNotBlank(plan.getWmsBasicWarehouse()), "wms_basic_warehouse_id", plan.getWmsBasicWarehouse());
        if (StringUtils.isNotBlank(plan.getWmsBasicWarehouseArea())) {
            wrapper.in("wms_basic_warehouse_area_id", plan.getWmsBasicWarehouseArea().split(","));
        }
//        wrapper.eq(StringUtils.isNotBlank(plan.getOwnerType()), "owner_type", plan.getOwnerType());
//        wrapper.eq(StringUtils.isNotBlank(plan.getOwner()), "owner_name", plan.getOwner());
        wrapper.eq(StringUtils.isNotBlank(plan.getCustomerId()), "wms_basic_supplier_id", plan.getCustomerId());
        wrapper.eq(StringUtils.isNotBlank(plan.getSupplierId()), "supplier", plan.getSupplierId());
        wrapper.eq(StringUtils.isNotBlank(plan.getProductOrderCode()), "product_code", plan.getProductOrderCode());
        List<WmsRepertory> list = wmsRepertoryService.list(wrapper);
        List<TakeStockPlanExecuteMaterial> materials = new ArrayList<>();
        for (WmsRepertory repertory : list) {
            TakeStockPlanExecuteMaterial material = BeanUtil.toBean(repertory, TakeStockPlanExecuteMaterial.class);
            material.setRepertoryId(repertory.getId());
            BasicMaterial byCode = basicMaterialService.getById(repertory.getMaterialId());
            material.setSpecification(Optional.ofNullable(byCode).map(BasicMaterial::getSpecification).orElse(null));
            material.setId(null);
            materials.add(material);
        }
        vo.setTakeStockPlanExecuteMaterialList(materials);
        if (StringUtils.isNotBlank(vo.getWmsBasicWarehouseGroupId())) {
            WmsBasicWarehouseGroup group = warehouseGroupService.getById(vo.getWmsBasicWarehouseGroupId());
            vo.setWmsBasicWarehouseGroupName(Optional.ofNullable(group).map(WmsBasicWarehouseGroup::getName).orElse(""));
        }
        return vo;
    }

    /**
     * 新增
     *
     * @param vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveExecute(TakeStockPlanExecuteAddVO vo) {
        // 盘点任务变为已执行
        TakeStockPlan plan = new TakeStockPlan();
        plan.setId(vo.getWmsTakeStockPlanId());
        plan.setExecuteFlag("1");
        if (vo.getCode().endsWith("-1")) {
            plan.setDocumentStatus("3");
        }
        takeStockPlanService.updateById(plan);
        // 保存盘点执行
        TakeStockPlanExecute takeStockPlanExecute = BeanUtil.toBean(vo, TakeStockPlanExecute.class);
        takeStockPlanExecute.setDocumentStatus("1");
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        takeStockPlanExecute.setOrganization(sysUser.getOrgCode());
        this.save(takeStockPlanExecute);
        // 保存盘点执行物料
        List<TakeStockPlanExecuteMaterial> list = vo.getTakeStockPlanExecuteMaterialList();
        for (TakeStockPlanExecuteMaterial material : list) {
            if (StringUtils.isBlank(material.getResult())) {
                if (StringUtils.isNotBlank(material.getInventoryProfit())) {
                    material.setResult("1");
                }
                if (StringUtils.isNotBlank(material.getInventoryLoss())) {
                    material.setResult("2");
                }
                if (StringUtils.isNotBlank(material.getRealCount()) && material.getStockQuantity() != null && new BigDecimal(material.getRealCount()).compareTo(material.getStockQuantity()) == 0) {
                    material.setResult("4");
                }
            }
            material.setTakeStockPlanExecuteId(takeStockPlanExecute.getId());
            material.setCreateBy(null);
            material.setCreateTime(null);
            material.setUpdateBy(null);
            material.setUpdateTime(null);
            material.setId(null);
            takeStockPlanExecuteMaterialMapper.insert(material);
        }
        return takeStockPlanExecute.getId();
    }

    /**
     * 编辑
     *
     * @param vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateExecute(TakeStockPlanExecuteAddVO vo) {
        TakeStockPlanExecute execute = BeanUtil.toBean(vo, TakeStockPlanExecute.class);
        this.updateById(execute);
//		if (TakeStockPlanStatusConstant.SUBMITTED.equals(vo.getDocumentStatus())) {
//			// 变更状态为已提交
//			return;
//		}
        List<TakeStockPlanExecuteMaterial> list = vo.getTakeStockPlanExecuteMaterialList();
        if (list == null) {
            return;
        }
        List<String> ids = list.stream().map(TakeStockPlanExecuteMaterial::getId).collect(Collectors.toList());
        // 删除之前非库存的物料
        List<TakeStockPlanExecuteMaterial> materialList = takeStockPlanExecuteMaterialService.list(new LambdaQueryWrapper<TakeStockPlanExecuteMaterial>()
                .eq(TakeStockPlanExecuteMaterial::getTakeStockPlanExecuteId, vo.getId())
                .isNull(TakeStockPlanExecuteMaterial::getRepertoryId));
        for (TakeStockPlanExecuteMaterial material : materialList) {
            if (StringUtils.isBlank(material.getRepertoryId()) && !ids.contains(material.getId())) {
                takeStockPlanExecuteMaterialService.removeById(material.getId());
            }
        }
        // 新增非库存的物料
        for (TakeStockPlanExecuteMaterial material : list) {
            if (StringUtils.isBlank(material.getResult())) {
                if (StringUtils.isNotBlank(material.getInventoryProfit())) {
                    material.setResult("1");
                }
                if (StringUtils.isNotBlank(material.getInventoryLoss())) {
                    material.setResult("2");
                }
                if (StringUtils.isNotBlank(material.getRealCount())) {
                    BigDecimal realCount = new BigDecimal(material.getRealCount());
                    if (material.getStockQuantity() != null && realCount.compareTo(material.getStockQuantity()) == 0) {
                        material.setResult("4");
                    }
                }
            }
            if (StringUtils.isBlank(material.getRealCount())) {
                material.setResult(null);
            }
            if (StringUtils.isNotBlank(material.getRepertoryId()) || StringUtils.isNotBlank(material.getId())) {
                takeStockPlanExecuteMaterialMapper.updateById(material);
                continue;
            }
            material.setTakeStockPlanExecuteId(vo.getId());
            takeStockPlanExecuteMaterialMapper.insert(material);
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Override
    public TakeStockPlanExecuteMaterialVO getExecuteById(String id) {
        TakeStockPlanExecute takeStockPlanExecute = this.getById(id);
        if (takeStockPlanExecute == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        TakeStockPlan plan = takeStockPlanService.getById(takeStockPlanExecute.getWmsTakeStockPlanId());
        TakeStockPlanExecuteMaterialVO vo = BeanUtil.toBean(plan, TakeStockPlanExecuteMaterialVO.class);
        vo.setCode(takeStockPlanExecute.getCode());
        vo.setExecuteDate(takeStockPlanExecute.getExecuteDate());
        vo.setGenerateFlag(takeStockPlanExecute.getGenerateFlag());
        vo.setDocumentStatus(takeStockPlanExecute.getDocumentStatus());
        vo.setDocumentType(takeStockPlanExecute.getDocumentType());
        vo.setWmsTakeStockPlanName(plan.getName());
        vo.setTakeStockPlanCode(plan.getCode());
        vo.setWmsTakeStockPlanId(takeStockPlanExecute.getWmsTakeStockPlanId());
        List<DictModel> type = iSysBaseAPI.getDictItems("take_stock_type");
        Map<String, String> typeMaps = type.stream().collect(Collectors.toMap(DictModel::getValue, DictModel::getText, (key1, key2) -> key2));
        List<DictModel> range = iSysBaseAPI.getDictItems("take_stock_range");
        Map<String, String> rangeMaps = range.stream().collect(Collectors.toMap(DictModel::getValue, DictModel::getText, (key1, key2) -> key2));
        vo.setTypeName(typeMaps.get(vo.getType()));
        vo.setRangeTypeName(rangeMaps.get(vo.getRangeType()));

        List<TakeStockPlanExecuteMaterial> materialList = takeStockPlanExecuteMaterialService.list(new LambdaQueryWrapper<TakeStockPlanExecuteMaterial>()
                .eq(TakeStockPlanExecuteMaterial::getTakeStockPlanExecuteId, id)
                .orderByAsc(TakeStockPlanExecuteMaterial::getCreateTime));
        Set<String> locationIds = materialList.stream().map(TakeStockPlanExecuteMaterial::getWmsBasicWarehouseAreaLocationId).collect(Collectors.toSet());
        Map<String, WmsBasicWarehouse> warehouseMap = warehouseService.list().stream().collect(Collectors.toMap(WmsBasicWarehouse::getId, Function.identity()));
        Map<String, WmsBasicWarehouseArea> areaMap = warehouseAreaService.list().stream().collect(Collectors.toMap(WmsBasicWarehouseArea::getId, Function.identity()));
        Map<String, WmsBasicWarehouseAreaLocation> locationMap = warehouseAreaLocationService.list(new LambdaQueryWrapper<WmsBasicWarehouseAreaLocation>()
                .in(WmsBasicWarehouseAreaLocation::getId, locationIds))
                .stream().collect(Collectors.toMap(WmsBasicWarehouseAreaLocation::getId, Function.identity()));
        Map<String, BasicUnit> unitMap = unitService.list().stream().collect(Collectors.toMap(BasicUnit::getId, Function.identity()));

        for (TakeStockPlanExecuteMaterial material : materialList) {
            WmsBasicWarehouse warehouse = warehouseMap.get(material.getWmsBasicWarehouseId());
            material.setWmsBasicWarehouseName(Optional.ofNullable(warehouse).map(WmsBasicWarehouse::getName).orElse(""));
            WmsBasicWarehouseArea area = areaMap.get(material.getWmsBasicWarehouseAreaId());
            material.setWmsBasicWarehouseAreaName(Optional.ofNullable(area).map(WmsBasicWarehouseArea::getName).orElse(""));
            WmsBasicWarehouseAreaLocation location = locationMap.get(material.getWmsBasicWarehouseAreaLocationId());
            material.setWmsBasicWarehouseAreaLocationName(Optional.ofNullable(location).map(WmsBasicWarehouseAreaLocation::getName).orElse(""));
            BasicUnit unit = unitMap.get(material.getWmsBasicUnitId());
            material.setWmsBasicUnitName(Optional.ofNullable(unit).map(BasicUnit::getName).orElse(""));
            BasicUnit unitSub = unitMap.get(material.getUnitSub());
            material.setUnitSubName(Optional.ofNullable(unitSub).map(BasicUnit::getName).orElse(""));
        }
        vo.setTakeStockPlanExecuteMaterialList(materialList);
        // 已生成盘盈单盘亏单返回编号
//        if ("1".equals(takeStockPlanExecute.getGenerateFlag())) {
//            List<TakeStockResult> list = takeStockResultService.list(new LambdaQueryWrapper<TakeStockResult>()
//                    .eq(TakeStockResult::getWmsTakeStockPlanExecuteId, id));
//            List<TakeStockResult> profits = list.stream().filter(a -> TakeStockResultConstant.INVENTORY_PROFIT.equals(a.getType())).collect(Collectors.toList());
//            List<TakeStockResult> losses = list.stream().filter(a -> TakeStockResultConstant.INVENTORY_LOSS.equals(a.getType())).collect(Collectors.toList());
//            if (CollectionUtils.isNotEmpty(profits)) {
//                vo.setInventoryProfitCode(profits.get(0).getCode());
//            }
//            if (CollectionUtils.isNotEmpty(losses)) {
//                vo.setInventoryLossCode(losses.get(0).getCode());
//            }
//        }
        return vo;
    }

    /**
     * 生成盘盈盘亏单
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTakeStockResult(String id) {
//        TakeStockPlanExecute byId = this.getById(id);
////		if (!TakeStockPlanStatusConstant.SUBMITTED.equals(byId.getDocumentStatus())) {
////			throw new JeecgBootException("单据状态不是已提交，不能生成盘盈盘亏单");
////		}
////		if ("1".equals(byId.getGenerateFlag())) {
////			throw new JeecgBootException("不能重复生成盘盈盘亏单");
////		}
//        // 更新是否生成盘盈或盘亏单状态
//        byId.setGenerateFlag("1");
//        byId.setDocumentStatus("3");
//
//        List<TakeStockPlanExecuteMaterial> list = takeStockPlanExecuteMaterialService.list(new LambdaQueryWrapper<TakeStockPlanExecuteMaterial>()
//                .eq(TakeStockPlanExecuteMaterial::getTakeStockPlanExecuteId, id));
//        List<String> inventoryProfits = new ArrayList<>();    //盘盈单
//        List<String> inventoryLosses = new ArrayList<>();    //盘亏单
//        for (TakeStockPlanExecuteMaterial material : list) {
//            if (StringUtils.isNotBlank(material.getInventoryProfit()) && !"0".equals(material.getInventoryProfit())) {
//                inventoryProfits.add(material.getId());
//            }
//            if (StringUtils.isNotBlank(material.getInventoryLoss()) && !"0".equals(material.getInventoryLoss())) {
//                inventoryLosses.add(material.getId());
//            }
//
//        }
//        // 盘盈单
//        if (CollectionUtils.isNotEmpty(inventoryProfits)) {
//            TakeStockResult inventoryProfit = new TakeStockResult();
//            inventoryProfit.setCode(FillRuleUtil.executeRule(FillRuleConstant.INVENTORY_PROFIT, new JSONObject()).toString());
//            inventoryProfit.setWmsTakeStockPlanExecuteId(id);
//            inventoryProfit.setType(TakeStockResultConstant.INVENTORY_PROFIT);
//            inventoryProfit.setWmsTakeStockPlanExecuteMaterialId(StringUtils.join(inventoryProfits, ","));
//            inventoryProfit.setDocumentStatus(TakeStockPlanStatusConstant.SUBMITTED);
//            takeStockResultService.save(inventoryProfit);
//            byId.setInventoryGainId(inventoryProfit.getId());
//        }
//        // 盘亏单
//        if (CollectionUtils.isNotEmpty(inventoryLosses)) {
//            TakeStockResult inventoryLoss = new TakeStockResult();
//            inventoryLoss.setCode(FillRuleUtil.executeRule(FillRuleConstant.INVENTORY_LOSS, new JSONObject()).toString());
//            inventoryLoss.setWmsTakeStockPlanExecuteId(id);
//            inventoryLoss.setType(TakeStockResultConstant.INVENTORY_LOSS);
//            inventoryLoss.setWmsTakeStockPlanExecuteMaterialId(StringUtils.join(inventoryLosses, ","));
//            inventoryLoss.setDocumentStatus(TakeStockPlanStatusConstant.SUBMITTED);
//            takeStockResultService.save(inventoryLoss);
//            byId.setInventoryLossId(inventoryLoss.getId());
//        }
//
//        this.updateById(byId);
    }

    /**
     * 复盘
     *
     * @param id
     * @param result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String replay(String id, List<String> result) {
        TakeStockPlanExecute execute = this.getById(id);
        TakeStockPlanExecute newCode = this.getOne(new LambdaQueryWrapper<TakeStockPlanExecute>()
                .like(TakeStockPlanExecute::getCode, execute.getCode().split("-")[0])
                .orderByDesc(TakeStockPlanExecute::getCreateTime)
                .last("limit 1"));
        String[] split = newCode.getCode().split("-");
        int i = Integer.parseInt(split[1]) + 1;

        List<TakeStockPlanExecuteMaterial> list = takeStockPlanExecuteMaterialService.list(new LambdaQueryWrapper<TakeStockPlanExecuteMaterial>()
                .eq(TakeStockPlanExecuteMaterial::getTakeStockPlanExecuteId, id));
        if (!result.contains("4")) {
            list = list.stream().filter(a -> result.contains(a.getResult())).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(list)) {
            throw new JeecgBootException("没有此类需要复盘的数据");
        }
        for (TakeStockPlanExecuteMaterial material : list) {
            material.setId(null);
            material.setCreateBy(null);
            material.setCreateTime(null);
            material.setUpdateBy(null);
            material.setUpdateTime(null);
            material.setRealCount(null);
            material.setRealCountAssistant(null);
            material.setInventoryProfit(null);
            material.setInventoryProfitAssistant(null);
            material.setInventoryLoss(null);
            material.setInventoryLossAssistant(null);
            material.setResult(null);
        }

        BaseFlowDto base = new BaseFlowDto();
        base.setBusinessType("take_job");
        base.setDocumentType("1");
        base.setInfoId("");
        PrintConfig config = printConfigService.getOne(new LambdaQueryWrapper<PrintConfig>()
                .eq(PrintConfig::getBusinessType, "take_job")
                .last("limit 1"));
        WmsDocumentTypeStatus typeStatus = documentTypeStatusService.getOne(new LambdaQueryWrapper<WmsDocumentTypeStatus>()
                .eq(WmsDocumentTypeStatus::getPrintConfigId, config.getId())
                .like(WmsDocumentTypeStatus::getName, "保存")
                .last("limit 1"));
        base.setCode(typeStatus.getCode());
        TakeStockPlanExecuteAddVO vo = new TakeStockPlanExecuteAddVO();
        vo.setWmsTakeStockPlanId(execute.getWmsTakeStockPlanId());
        vo.setCode(split[0] + "-" + i);
        vo.setExecuteDate(execute.getExecuteDate());
        vo.setDocumentStatus("1");
        vo.setDocumentType(execute.getDocumentType());
        vo.setReplayFlag("1");
        vo.setTakeStockPlanExecuteMaterialList(list);
        base.setData(vo);
        workFlowService.commit(base);
        return base.getInfoId();
    }

    /**
     * 盘点分析分页
     *
     * @param page
     * @param takeStockPlanExecute
     * @return
     */
    @Override
    public Page<TakeStockPlanExecuteVO> pageAnalysis(Page<TakeStockPlanExecuteVO> page, TakeStockPlanExecuteVO takeStockPlanExecute) {
        return page.setRecords(takeStockPlanExecuteMapper.pageAnalysis(page, takeStockPlanExecute));
    }

    /**
     * 盘点对比
     * @param takeStockPlanId
     * @return
     */
    @Override
    public TakeStockPlanExecuteMaterialVO contrast(String takeStockPlanId) {
        List<TakeStockPlanExecute> list = this.list(new LambdaQueryWrapper<TakeStockPlanExecute>()
                .eq(TakeStockPlanExecute::getWmsTakeStockPlanId, takeStockPlanId)
                .orderByAsc(TakeStockPlanExecute::getCode));
        TakeStockPlanExecuteMaterialVO execute = this.getExecuteById(list.get(0).getId());
        List<TakeStockPlanExecuteMaterial> materials1 = execute.getTakeStockPlanExecuteMaterialList();
        for (TakeStockPlanExecuteMaterial material : materials1) {
            material.setNumber1(material.getRealCount());
        }
        List<TakeStockPlanExecuteMaterial> materials = new ArrayList<>(materials1);
        // 复盘1
        if (list.size() > 1) {
            List<TakeStockPlanExecuteMaterial> materials2 = takeStockPlanExecuteMaterialService.selectByMainId(list.get(1).getId());
            for (TakeStockPlanExecuteMaterial material2 : materials2) {
                for (TakeStockPlanExecuteMaterial material : materials) {
                    if (Objects.equals(material.getBatchCode(), material2.getBatchCode()) &&
                            Objects.equals(material.getMaterialCode(), material2.getMaterialCode()) &&
                            Objects.equals(material.getWmsBasicWarehouseAreaId(), material2.getWmsBasicWarehouseAreaId()) &&
                            Objects.equals(material.getWmsBasicWarehouseAreaLocationId(), material2.getWmsBasicWarehouseAreaLocationId()) &&
                            Objects.equals(material.getOwnerName(), material2.getOwnerName())) {
                        material.setNumber2(material2.getRealCount());
                        break;
                    }
                }
                if (materials.stream().noneMatch(a -> Objects.equals(a.getBatchCode(), material2.getBatchCode()) &&
                        Objects.equals(a.getMaterialCode(), material2.getMaterialCode()) &&
                        Objects.equals(a.getWmsBasicWarehouseAreaId(), material2.getWmsBasicWarehouseAreaId()) &&
                        Objects.equals(a.getWmsBasicWarehouseAreaLocationId(), material2.getWmsBasicWarehouseAreaLocationId()) &&
                        Objects.equals(a.getOwnerName(), material2.getOwnerName()))) {
                    material2.setNumber2(material2.getRealCount());
                    materials.add(material2);
                }

            }
        }
        // 复盘2
        if (list.size() > 2) {
            List<TakeStockPlanExecuteMaterial> materials3 = takeStockPlanExecuteMaterialService.selectByMainId(list.get(2).getId());
            for (TakeStockPlanExecuteMaterial material3 : materials3) {
                for (TakeStockPlanExecuteMaterial material : materials) {
                    if (Objects.equals(material.getBatchCode(), material3.getBatchCode()) &&
                            Objects.equals(material.getMaterialCode(), material3.getMaterialCode()) &&
                            Objects.equals(material.getWmsBasicWarehouseAreaId(), material3.getWmsBasicWarehouseAreaId()) &&
                            Objects.equals(material.getWmsBasicWarehouseAreaLocationId(), material3.getWmsBasicWarehouseAreaLocationId()) &&
                            Objects.equals(material.getOwnerName(), material3.getOwnerName())) {
                        material.setNumber3(material3.getRealCount());
                        break;
                    }
                }
                if (materials.stream().noneMatch(a -> Objects.equals(a.getBatchCode(), material3.getBatchCode()) &&
                        Objects.equals(a.getMaterialCode(), material3.getMaterialCode()) &&
                        Objects.equals(a.getWmsBasicWarehouseAreaId(), material3.getWmsBasicWarehouseAreaId()) &&
                        Objects.equals(a.getWmsBasicWarehouseAreaLocationId(), material3.getWmsBasicWarehouseAreaLocationId()) &&
                        Objects.equals(a.getOwnerName(), material3.getOwnerName()))) {
                    material3.setNumber3(material3.getRealCount());
                    materials.add(material3);
                }
            }
        }

        for (TakeStockPlanExecuteMaterial material : materials1) {
            if (StringUtils.isNotBlank(material.getNumber1())) {
                if (new BigDecimal(material.getNumber1()).compareTo(material.getStockQuantity()) == 1) {
                    material.setInventoryProfit(String.valueOf(new BigDecimal(material.getNumber1()).subtract(material.getStockQuantity())));
                }
                if (new BigDecimal(material.getNumber1()).compareTo(material.getStockQuantity()) == -1) {
                    material.setInventoryLoss(String.valueOf(material.getStockQuantity().subtract(new BigDecimal(material.getNumber1()))));
                }
//                if (new BigDecimal(material.getNumber1()).compareTo(material.getStockQuantity()) == 0) {
//                    material.setInventoryProfit(null);
//                    material.setInventoryLoss(null);
//                }
            }
            if (StringUtils.isNotBlank(material.getNumber2())) {
                material.setInventoryProfit(null);
                material.setInventoryLoss(null);
                if (new BigDecimal(material.getNumber2()).compareTo(material.getStockQuantity()) == 1) {
                    material.setInventoryProfit(String.valueOf(new BigDecimal(material.getNumber2()).subtract(material.getStockQuantity())));
                }
                if (new BigDecimal(material.getNumber2()).compareTo(material.getStockQuantity()) == -1) {
                    material.setInventoryLoss(String.valueOf(material.getStockQuantity().subtract(new BigDecimal(material.getNumber2()))));
                }
            }
            if (StringUtils.isNotBlank(material.getNumber3())) {
                material.setInventoryProfit(null);
                material.setInventoryLoss(null);
                if (new BigDecimal(material.getNumber3()).compareTo(material.getStockQuantity()) == 1) {
                    material.setInventoryProfit(String.valueOf(new BigDecimal(material.getNumber3()).subtract(material.getStockQuantity())));
                }
                if (new BigDecimal(material.getNumber3()).compareTo(material.getStockQuantity()) == -1) {
                    material.setInventoryLoss(String.valueOf(material.getStockQuantity().subtract(new BigDecimal(material.getNumber3()))));
                }
            }
        }
        execute.setTakeStockPlanExecuteMaterialList(materials);
        execute.setWmsTakeStockPlanId(takeStockPlanId);
        return execute;
    }

    /**
     * 保存盘点对比
     * @param list
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveContrast(List<TakeStockPlanExecuteMaterial> list) {
        for (TakeStockPlanExecuteMaterial material : list) {
            takeStockPlanExecuteMaterialService.update(new LambdaUpdateWrapper<TakeStockPlanExecuteMaterial>()
                    .eq(TakeStockPlanExecuteMaterial::getId, material.getId())
                    .set(TakeStockPlanExecuteMaterial::getRemark, material.getRemark()));
        }
    }

    /**
     * 盘点差异处理
     * @param takeStockPlanId
     * @return
     */
    @Override
    public TakeStockPlanExecuteMaterialVO difference(String takeStockPlanId) {
        List<TakeStockPlanExecute> list = this.list(new LambdaQueryWrapper<TakeStockPlanExecute>()
                .eq(TakeStockPlanExecute::getWmsTakeStockPlanId, takeStockPlanId)
                .orderByDesc(TakeStockPlanExecute::getCode));
        if (CollectionUtils.isEmpty(list)) {
            throw new JeecgBootException("该盘点任务没有盘点作业，不能生成盘点差异处理单！");
        }
        TakeStockPlanExecuteMaterialVO execute = this.getExecuteById(list.get(0).getId());
        execute.setWmsTakeStockPlanId(takeStockPlanId);
        execute.setTakeStockPlanExecuteId(list.get(0).getId());
        execute.setDocumentStatus("1");
        List<TakeStockPlanExecuteMaterial> materialList = execute.getTakeStockPlanExecuteMaterialList();
        for (TakeStockPlanExecuteMaterial material : materialList) {
            material.setId(null);
            material.setCreateTime(null);
            material.setCreateBy(null);
            material.setUpdateTime(null);
            material.setUpdateBy(null);
        }
        return execute;
    }

    /**
     * 根据物料查询账存数量
     * @param material
     * @return
     */
    @Override
    public BigDecimal getStockQuantity(TakeStockPlanExecuteMaterial material) {
        if (StringUtils.isBlank(material.getMaterialCode())) {
            return null;
        }
        List<WmsRepertory> list = wmsRepertoryService.list(new LambdaQueryWrapper<WmsRepertory>()
                .eq(StringUtils.isNotBlank(material.getWmsBasicWarehouseId()), WmsRepertory::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId())
                .eq(StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaId()), WmsRepertory::getWmsBasicWarehouseAreaId, material.getWmsBasicWarehouseAreaId())
                .eq(StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaLocationId()), WmsRepertory::getWmsBasicWarehouseAreaLocationId, material.getWmsBasicWarehouseAreaLocationId())
                .eq(StringUtils.isNotBlank(material.getBatchCode()), WmsRepertory::getBatchCode, material.getBatchCode())
                .eq(StringUtils.isNotBlank(material.getMaterialCode()), WmsRepertory::getMaterialCode, material.getMaterialCode()));
        if (CollectionUtils.isEmpty(list)) {
            return new BigDecimal("0");
        }
        if (list.size() == 1) {
            return list.get(0).getStockQuantity();
        }
        return null;
    }

    /**
     * 导入物料明细
     * @param file
     * @param id
     * @return
     */
    @Override
    public Result<List<TakeStockPlanDifferenceMaterial>> importExcel(MultipartFile file, String id) {
        if (ObjectUtil.isNotEmpty(file)) {
            if (!file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xlx")) {
                return Result.error("文件格式错误！");
            }
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setNeedSave(true);
        try {
            TakeStockPlan plan = takeStockPlanService.getById(id);
            String organization = Optional.ofNullable(plan).map(TakeStockPlan::getOrganization).orElse("");
            List<TakeStockPlanExecuteMaterial> executeMaterials = takeStockPlanExecuteMaterialService.selectByMainId(id);
            List<TakeStockPlanDifferenceMaterial> materials = new ArrayList<>();
            for (TakeStockPlanExecuteMaterial material : executeMaterials) {
                TakeStockPlanDifferenceMaterial differenceMaterial = BeanUtil.copyProperties(material, TakeStockPlanDifferenceMaterial.class);
                materials.add(differenceMaterial);
            }

            List<TakeStockPlanDifferenceMaterial> list = ExcelImportUtil.importExcel(file.getInputStream(), TakeStockPlanDifferenceMaterial.class, params);
            List<String> errorLines = new ArrayList<>();
            List<TakeStockPlanDifferenceMaterial> successList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                TakeStockPlanDifferenceMaterial material = list.get(i);
                if (StringUtils.isBlank(material.getMaterialCode()) || StringUtils.isBlank(material.getWmsBasicWarehouseId()) || StringUtils.isBlank(material.getRealCount())) {
                    errorLines.add("第" + (i+2) + "行有必填字段未填");
                    continue;
                }
                if (material.getRealCount().startsWith("-") || (StringUtils.isNotBlank(material.getRealCountAssistant()) && material.getRealCountAssistant().startsWith("-"))) {
                    errorLines.add("第" + (i+2) + "行实盘数量和实盘数量(辅单位)不能填负数");
                    continue;
                }
                // 批次号
                if (StringUtils.isNotBlank(material.getBatchCode())) {
                    // 判断重复
                    List<TakeStockPlanDifferenceMaterial> collect = materials.stream().filter(a -> Objects.equals(material.getBatchCode(), a.getBatchCode())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(collect)) {
                        // 重复则覆盖实盘数量、实盘数量（辅单位）
                        collect.get(0).setRealCount(material.getRealCount());
                        collect.get(0).setRealCountAssistant(material.getRealCountAssistant());
                        successList.add(collect.get(0));
                        continue;
                    }
                    List<WmsRepertory> repertories = repertoryMapper.selectList(new LambdaQueryWrapper<WmsRepertory>()
                            .eq(WmsRepertory::getBatchCode, material.getBatchCode()));
                    if (CollectionUtils.isNotEmpty(repertories)) {
                        BeanUtil.copyProperties(repertories.get(0), material);
                        material.setRepertoryId(repertories.get(0).getId());
                    } else {
                        material.setStockQuantity(new BigDecimal("0"));
                    }
                } else {
                    // 判断重复
                    List<TakeStockPlanDifferenceMaterial> collect = materials.stream().filter(a -> Objects.equals(material.getMaterialCode(), a.getMaterialCode())
                            && Objects.equals(material.getWmsBasicWarehouseId(), a.getWmsBasicWarehouseId())
                            && Objects.equals(material.getWmsBasicWarehouseAreaId(), a.getWmsBasicWarehouseAreaId())
                            && Objects.equals(material.getWmsBasicWarehouseAreaLocationId(), a.getWmsBasicWarehouseAreaLocationId())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(collect)) {
                        // 重复则覆盖实盘数量、实盘数量（辅单位）
                        collect.get(0).setRealCount(material.getRealCount());
                        collect.get(0).setRealCountAssistant(material.getRealCountAssistant());
                        successList.add(collect.get(0));
                        continue;
                    }
                    List<WmsRepertory> repertories = repertoryMapper.selectList(new LambdaQueryWrapper<WmsRepertory>()
                            .eq(WmsRepertory::getMaterialCode, material.getMaterialCode())
                            .eq(WmsRepertory::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId())
                            .eq(WmsRepertory::getWmsBasicWarehouseAreaId, material.getWmsBasicWarehouseAreaId())
                            .eq(WmsRepertory::getWmsBasicWarehouseAreaLocationId, material.getWmsBasicWarehouseAreaLocationId()));
                    if (CollectionUtils.isNotEmpty(repertories)) {
                        material.setStockQuantity(repertories.get(0).getStockQuantity());
                        material.setStockQuantitySub(repertories.get(0).getStockQuantitySub());
                    } else {
                        material.setStockQuantity(new BigDecimal("0"));
                    }
                }
                // 计算盘盈盘亏
                BigDecimal subtract = new BigDecimal(material.getRealCount()).subtract(material.getStockQuantity());
                if (subtract.compareTo(new BigDecimal("0")) == 1) {
                    material.setResult("1");
                    material.setInventoryProfit(subtract.stripTrailingZeros().toPlainString());
                } else if (subtract.compareTo(new BigDecimal("0")) == -1) {
                    material.setResult("2");
                    material.setInventoryLoss(subtract.abs().stripTrailingZeros().toPlainString());
                } else {
                    material.setResult("4");
                }
                // 计算盘盈盘亏辅单位
                if (material.getStockQuantitySub() == null) {
                    material.setStockQuantitySub(new BigDecimal("0"));
                }
                if (StringUtils.isNotBlank(material.getRealCountAssistant()) && material.getStockQuantitySub() != null) {
                    BigDecimal sub = new BigDecimal(material.getRealCountAssistant()).subtract(material.getStockQuantitySub());
                    if (sub.compareTo(new BigDecimal("0")) == 1) {
                        material.setInventoryProfitAssistant(sub.stripTrailingZeros().toPlainString());
                    } else if (sub.compareTo(new BigDecimal("0")) == -1) {
                        material.setInventoryLossAssistant(sub.abs().stripTrailingZeros().toPlainString());
                    }
                }
                if (StringUtils.isBlank(material.getRepertoryId())) {
                    // 物料
                    BasicMaterial byCode = basicMaterialService.getByCode(material.getMaterialCode());
                    if (byCode == null) {
                        errorLines.add("第" + (i+2) + "行数据物料编码信息不存在");
                        continue;
                    }
                    material.setMaterialId(byCode.getId());
                    material.setMaterialName(byCode.getName());
                    material.setSpecification(byCode.getSpecification());
                    material.setWmsBasicUnitId(byCode.getInventoryUnitId());
                    material.setUnitSub(byCode.getAssistantUnitId());
                    // 仓库校验
                    WmsBasicWarehouse warehouse = warehouseMapper.selectById(material.getWmsBasicWarehouseId());
                    if (warehouse == null) {
                        errorLines.add("第" + (i+2) + "行数据仓库信息不存在");
                        continue;
                    }
                    if (!ObjectUtil.equal(warehouse.getSysOrgCode(), organization)) {
                        errorLines.add("第" + (i+2) + "行数据中该组织下不存在该仓库");
                        continue;
                    }
                    if ("N".equals(warehouse.getIsUseArea())) {
                        material.setWmsBasicWarehouseAreaId(null);
                        material.setWmsBasicWarehouseAreaLocationId(null);
                    } else {
                        if (StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaId())) {
                            WmsBasicWarehouseArea area = warehouseAreaMapper.selectById(material.getWmsBasicWarehouseAreaId());
                            if (area == null) {
                                errorLines.add("第" + (i + 2) + "行数据库区信息不存在");
                                continue;
                            }
                            List<WmsBasicWarehouseArea> areas = warehouseAreaMapper.selectList(new LambdaQueryWrapper<WmsBasicWarehouseArea>()
                                    .eq(WmsBasicWarehouseArea::getName, area.getName())
                                    .eq(WmsBasicWarehouseArea::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId()));
                            if (CollectionUtils.isEmpty(areas)) {
                                errorLines.add("第" + (i + 2) + "行数据库区信息不存在");
                                continue;
                            }
                            material.setWmsBasicWarehouseAreaId(areas.get(0).getId());
                            if (!"0".equals(areas.get(0).getIsUseLocation())) {
                                if (StringUtils.isNotBlank(material.getWmsBasicWarehouseAreaLocationId())) {
                                    WmsBasicWarehouseAreaLocation location = warehouseAreaLocationMapper.selectById(material.getWmsBasicWarehouseAreaLocationId());
                                    if (location == null) {
                                        errorLines.add("第" + (i + 2) + "行数据库位信息不存在");
                                        continue;
                                    }
                                    List<WmsBasicWarehouseAreaLocation> locations = warehouseAreaLocationMapper.selectList(new LambdaQueryWrapper<WmsBasicWarehouseAreaLocation>()
                                            .eq(WmsBasicWarehouseAreaLocation::getName, location.getName())
                                            .eq(WmsBasicWarehouseAreaLocation::getWmsBasicWarehouseAreaId, material.getWmsBasicWarehouseAreaId()));
                                    if (CollectionUtils.isEmpty(locations)) {
                                        errorLines.add("第" + (i + 2) + "行数据库位信息不存在");
                                        continue;
                                    }
                                    material.setWmsBasicWarehouseAreaLocationId(locations.get(0).getId());
                                }
                            } else {
                                material.setWmsBasicWarehouseAreaLocationId(null);
                            }
                        }
                    }
                }
                successList.add(material);
            }
            Result<List<TakeStockPlanDifferenceMaterial>> r = new Result();
            r.setSuccess(true);
            r.setCode(CommonConstant.SC_OK_200);
            r.setResult(successList);
            if (errorLines.size() > 0) {
                r.setSuccess(false);
                r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500);
                r.setMessage(StringUtils.join(errorLines, "，"));
            } else {
                r.setMessage("文件导入成功！");
            }
            return r;
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return Result.error("文件导入失败:"+e.getMessage());
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 物料明细合并取并集
     * @param materials1
     * @param materials2
     * @return
     */
    private void mergeMaterial(List<TakeStockPlanExecuteMaterial> materials1, List<TakeStockPlanExecuteMaterial> materials2) {
        List<TakeStockPlanExecuteMaterial> materials = new ArrayList<>(materials1);
        for (TakeStockPlanExecuteMaterial material2 : materials2) {
            if (materials.stream().anyMatch(a -> Objects.equals(a.getBatchCode(), material2.getBatchCode()) &&
                    Objects.equals(a.getWmsBasicWarehouseAreaId(), material2.getWmsBasicWarehouseAreaId()) &&
                    Objects.equals(a.getWmsBasicWarehouseAreaLocationId(), material2.getWmsBasicWarehouseAreaLocationId()) &&
                    Objects.equals(a.getOwnerName(), material2.getOwnerName()))) {
                continue;
            }
            materials1.add(material2);
        }
    }
}
